from bs4 import BeautifulSoup
import requests
import warnings
import urllib3
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from docx import Document
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
from selenium.webdriver.edge.service import Service

# 添加超链接的函数
def add_hyperlink(paragraph, text, url):
    """
    在段落中添加超链接，并设置为蓝色、下划线样式
    """
    part = paragraph.part
    r_id = part.relate_to(
        url,
        "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
        is_external=True
    )

    hyperlink = OxmlElement('w:hyperlink')
    hyperlink.set(qn('r:id'), r_id)

    new_run = OxmlElement('w:r')
    r_pr = OxmlElement('w:rPr')  # 运行属性

    # 设置超链接颜色为蓝色 (RGB值 0000FF)
    color = OxmlElement('w:color')
    color.set(qn('w:val'), '0000FF')  # 蓝色
    r_pr.append(color)

    # 设置下划线
    u = OxmlElement('w:u')
    u.set(qn('w:val'), 'single')  # 单下划线
    r_pr.append(u)

    new_run.append(r_pr)
    new_run.text = text
    hyperlink.append(new_run)
    paragraph._p.append(hyperlink)

    return hyperlink


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 创建一个Word文档
doc = Document()
doc.add_heading('文章列表', 0)  # 添加文档标题

try:
    service = Service(executable_path=r"D:\webdriver\edgedriver_win641\msedgedriver.exe")
    driver = webdriver.Edge(service=service)
    driver.get('https://mp.yiban.cn/app/login')
    time.sleep(2)
    input_elements = driver.find_elements(By.CSS_SELECTOR, '.mdc-text-field__input')
    response = requests.get("https://mp.yiban.cn/app/dashboard", headers=headers, verify=False)

    html = response.text
    soup = BeautifulSoup(html, "html.parser")
    a_tags = soup.findAll('a', href=True)
    links_titles = {}

    if len(input_elements) >= 2:
        input_elements[0].send_keys('18340855498')
        input_elements[1].send_keys('Wsqyxd23!')

    wait = WebDriverWait(driver, 10)
    button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".mdc-button")))
    button.click()
    c = input()
    if c:
        pass
    time.sleep(2)
    link = wait.until(EC.element_to_be_clickable(
        (By.XPATH, "/html/body/div/div[2]/div[1]/aside/div/div[3]/div[1]")))
    link.click()
    link_2 = wait.until(EC.element_to_be_clickable(
        (By.XPATH, "/html/body/div/div[2]/div[1]/aside/div/div[3]/div[2]/nav/a[2]")))
    link_2.click()
    time.sleep(2)
    k = 1
    num = 4
    for _ in range(num):
        elements = driver.find_elements(By.CSS_SELECTOR, 'a[href^="https://s.yiban.cn/"]')

        # 遍历元素并打印出链接和标题
        for element in elements:
            link = element.get_attribute('href')
            title = element.text
            print(f"{k}. {title}")
            print(f"   {link}")
            # 将标题和链接添加到Word文档中
            p = doc.add_paragraph()  # 添加标题
            p.add_run(f"{k}. {title}").bold = True  # 标题加粗
            p = doc.add_paragraph()  # 添加超链接
            add_hyperlink(p, link, link)  # 添加超链接
            k += 1

        link_2 = wait.until(EC.element_to_be_clickable(
            (By.XPATH, "/html/body/div[1]/div[2]/div[2]/div[2]/div[2]/div[2]/div/div[1]/button[2]/div")))
        link_2.click()
        time.sleep(2)

finally:
    # 保存Word文档
    doc.save('articles.docx')
    print("文章标题和链接已保存到 articles.docx")
    driver.quit()